<?php
namespace globalunit\utils;

use globalunit\utils\EsHelper;

class EsClient
{
     private $es = null;
     private $config = null;
     public function __construct($config)
     {
         $config['type'] = '_doc';
         $this->config = $config;
     }

     //新增文档
     public function add($body)
     {
         if(!isset($body['id'])){
             return false;
         }
        $this->config['id'] = $body['id'];
        $this->es = new EsHelper($this->config);
        $res = $this->es->add($body);
         if($res['statusCode'] != 201){
             return false;
         }
         return $res['result']['_id'];
     }

    //删除文档
     public function del($id)
     {
         $this->es = new EsHelper($this->config);
         $res = $this->es->delete($id);
         if($res['statusCode'] != 200){
             return false;
         }
         return true;
     }
    //修改文档
    public function save($id, $param)
    {
        $this->es = new EsHelper($this->config);
        $res = $this->es->save($id, ['doc' => $param]);
        if($res['statusCode'] != 200){
            return false;
        }
        return true;
    }

    //修改文档
    public function get($query)
    {
        $this->es = new EsHelper($this->config);
        $res = $this->es->get($query);
        if($res['statusCode'] != 200){
            return [];
        }
        return $res['result']['_source'];
    }

    //查询文档
    public function search($query)
    {
        $this->es = new EsHelper($this->config);
        $res = $this->es->search($query);
        if($res['statusCode'] != 200){
            return [];
        }
        return $res['result']['hits']['hits'];
    }

    //删除索引
    public function drop()
    {
        $this->es = new EsHelper($this->config);
        $res = $this->es->drop();
        if($res['statusCode'] != 200){
            return false;
        }
        return true;
    }

    public function count($query)
    {
        $this->es = new EsHelper($this->config);
        $res = $this->es->count($query);
        if($res['statusCode'] != 200){
            return false;
        }
        return $res['result']['count'];
    }
}